package com.example.springboot.service.impl;

import com.example.springboot.controller.request.BasePageRequest;
import com.example.springboot.controller.request.LoginRequest;
import com.example.springboot.controller.request.PasswordRequest;
import com.example.springboot.controller.request.UserPageRequest;
import com.example.springboot.dto.UserLoginDTO;
import com.example.springboot.entity.User;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.mapper.UserMapper;
import com.example.springboot.service.UserService;
import com.example.springboot.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * ClassName:UserServiceImpl
 * Package:com.example.springboot.service.impl
 * Description:
 *
 * @Author: Gao
 * @Create: 2023/2/1 - 16:32
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public List<User> list() {

        return userMapper.list();
    }

    @Override
    public Object page(BasePageRequest basePageRequest) {
        PageHelper.startPage(basePageRequest.getPageNum(), basePageRequest.getPageSize());
        List<User> users = userMapper.listByCondition(basePageRequest);
        return new PageInfo<>(users);
    }

    @Override
    public void save(User user) {
        user.setStatus(true);
        userMapper.save(user);
    }

    @Override
    public void deleteById(int id) {
        userMapper.deleteById(id);
    }

    @Override
    public UserLoginDTO login(LoginRequest request) {
        User user = userMapper.getByNameAndPassword(request);
        if (user == null) {
            throw new ServiceException("用户名或密码错误");
        }
        if (!user.isStatus()) {
            throw new ServiceException("当前账号已被禁用，请联系其他管理员");
        }
        UserLoginDTO loginDTO = new UserLoginDTO();
        BeanUtils.copyProperties(user, loginDTO);
        String token = TokenUtils.genToken(String.valueOf(user.getId()), user.getPassword());
        loginDTO.setToken(token);
        return loginDTO;
    }
    @Override
    public void changePassword(PasswordRequest request) {
        int i = userMapper.updatePassword(request);
        if (i <= 0) {
            throw new ServiceException("修改密码失败");
        }
    }

    @Override
    public void update(User user) {
        user.setUpdatetime( new Date());
        userMapper.updateById(user);
    }

    @Override
    public User getById(int id) {
        return userMapper.getById(id);
    }
}
